/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PrihlasovaciDialog.java
 *
 * Created on 26.11.2011, 14:29:19
 */
package gui;

import database.DatabazovaChyba;
import database.DbService;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import system.Launcher;
import uzivatele.*;


/**
 *
 * @author Johny007
 */
public class PrihlasovaciDialog extends javax.swing.JFrame {

    private Launcher launcher;
    private DbService database;

    /** Creates new form PrihlasovaciDialog */
    public PrihlasovaciDialog() {

        this.launcher = Launcher.getInstance();
        this.database = launcher.getDatabase();
        initComponents();
        Launcher.getInstance().setOknoDoprostred(this);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        TextFieldUsername = new javax.swing.JTextField();
        PasswordField = new javax.swing.JPasswordField();
        ButtonLogin = new javax.swing.JButton();
        ButtonExit = new javax.swing.JButton();
        ButtonHelp = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Uživatelské jméno:");

        jLabel2.setText("Heslo:");

        ButtonLogin.setText("Přihlásit");
        ButtonLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonLoginActionPerformed(evt);
            }
        });

        ButtonExit.setText("Konec");
        ButtonExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonExitActionPerformed(evt);
            }
        });

        ButtonHelp.setText("Pomoc");
        ButtonHelp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonHelpActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ButtonLogin)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ButtonExit)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ButtonHelp))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(PasswordField)
                        .addComponent(TextFieldUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(TextFieldUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ButtonLogin)
                    .addComponent(ButtonExit)
                    .addComponent(ButtonHelp))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Zkontroluji ze uzivatelske jmeno se vyskytuje v DB. Zkontrolujeme heslo,
     * pokracujeme vytvorenim Hlavniho okna s prihlasenym uzivatelem.
     * @param evt 
     */
    private void ButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonLoginActionPerformed
        String username = this.TextFieldUsername.getText();
        String passwd = new String(this.PasswordField.getPassword());
        if (username.equals("")) {
            JOptionPane.showMessageDialog(this.getFocusOwner(), "Zadejte nejdříve uživatelské jméno.");
            return;
        }
        if (passwd.equals("")) {
            JOptionPane.showMessageDialog(this.getFocusOwner(), "Zadejte nejdříve heslo.");
            return;
        }
        try {

            if (database.userNameExists(username)) {
                if (database.passwordMatch(username, passwd)) {
                    String podminka = "WHERE email='" + username + "'";
                    ArrayList<Uzivatel> seznamOdpovidajichUzivatelu = database.vyberUzivatele(podminka);
                    if (seznamOdpovidajichUzivatelu.size() >= 1) {
                        Launcher.getInstance().setUzivatel(seznamOdpovidajichUzivatelu.get(0));
                        java.awt.EventQueue.invokeLater(new Runnable() {

                            public void run() { 
                                HlavniOkno okno = new HlavniOkno();
                                Launcher.getInstance().setHlavniOkno(okno);
                                okno.setVisible(true);
                            }
                        });
                        this.dispose();
                    }
                } else {
                    JOptionPane.showMessageDialog(this.getFocusOwner(), "Nesprávné heslo, opakujte zadání.");
                }
            }else{
                JOptionPane.showMessageDialog(this.getFocusOwner(), "Zadané uživatelské jméno neexistuje! Zadejte znovu.");
                this.PasswordField.setText("");
                this.TextFieldUsername.setText("");
            }
        } catch (DatabazovaChyba ex) {
            JOptionPane.showMessageDialog(this.getFocusOwner(), "Chyba v komunikaci s databází\n"+ex.getMessage());

        }
    }//GEN-LAST:event_ButtonLoginActionPerformed

    private void ButtonHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonHelpActionPerformed
        JOptionPane.showMessageDialog(this.getFocusOwner(),
                "Pokud máte problémy s přihlášením,"
                + " nebo se chce zaregistrovat. \n"
                + "Kontaktujte administrátora na adrese admin@mojefirma.cz.");
    }//GEN-LAST:event_ButtonHelpActionPerformed


    private void ButtonExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonExitActionPerformed
        this.dispose();
    }//GEN-LAST:event_ButtonExitActionPerformed


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PrihlasovaciDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PrihlasovaciDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PrihlasovaciDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PrihlasovaciDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PrihlasovaciDialog().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonExit;
    private javax.swing.JButton ButtonHelp;
    private javax.swing.JButton ButtonLogin;
    private javax.swing.JPasswordField PasswordField;
    private javax.swing.JTextField TextFieldUsername;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration//GEN-END:variables
}
